package com.manager.core.module.manager.service;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.manager.commons.log.LogFactory;
import com.manager.user.module.LoginController;
import com.manager.user.module.platform.core.dao.PlatformUserDao;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.code.kaptcha.Constants;
import com.manager.commons.encrypt.md5.MD5;
import com.manager.commons.utils.StringUtil;
import com.manager.user.module.platform.core.entity.UserInfo;
import com.manager.core.shiro.config.ShiroConfig;
import com.manager.core.shiro.config.ShiroUtil;
import com.manager.core.shiro.core.entity.LoginUser;
import com.manager.core.web.json.AjaxJson;

@Service
public class LoginService {
    protected static final Logger logger = LogFactory.getLogger(LoginController.class);
    @Autowired
    private PlatformUserDao puDao;

    /**
     * 登录
     *
     * @param account
     * @return
     */
    private UserInfo login(String account) {
        return puDao.login(new HashMap<String, Object>() {
            private static final long serialVersionUID = 2897617740011146915L;

            {
                put("account", account);
            }
        });
    }


    /**
     * 退出登录
     *
     * @param session
     * @param request
     * @param subject
     * @throws Exception
     */
    public void logout(HttpSession session, HttpServletRequest request, Subject subject) throws Exception {
        session.removeAttribute("");
        if (null != subject) {
            subject.logout();
        }
    }


    /**
     * 登录
     *
     * @param user
     * @param session
     * @param request
     * @param subject
     * @return
     * @throws Exception
     */
    public AjaxJson doLogin(LoginUser user, HttpSession session, HttpServletRequest request, Subject subject) throws Exception {
        if (StringUtil.isBlank(user.getAccount())) {
            return new AjaxJson("用户名或密码错误！");
        }
        if (StringUtil.isBlank(user.getPassword())) {
            return new AjaxJson("用户名或密码错误！");
        }
        if (StringUtil.isBlank(user.getCode())) {
            return new AjaxJson("验证码错误！");
        }
        Object kskCode = session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (!user.getCode().equals(String.valueOf(kskCode))) {
            return new AjaxJson("验证码错误！");
        }
        int f = 0;
        String msg = "认证失败";
        String password = MD5.md5(user.getPassword());
        logger.debug(password + "----------------------------md5");
        UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(), password);
        // Shiro身份验证
        subject.login(token);
        if (subject.isAuthenticated()) {
            // 查询用户信息
            UserInfo pu = login(user.getAccount());
            if (null != pu) {
                puDao.updateLoginTime(pu.getId());
                session.setAttribute(ShiroConfig.CURRENTNAME, pu.getName());
                ShiroUtil.setCurrentRole();
                f = 1;
                msg = "登录成功";
                // 验证码只使用一次，将验证码移除，防止复用
                session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
            }
        }

        return new AjaxJson(f, msg);
    }

}